package com.kuding.ecs.components;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.ecs.model.v20140526.DescribeInstancesRequest;
import com.aliyuncs.ecs.model.v20140526.DescribeInstancesResponse;
import com.aliyuncs.ecs.model.v20140526.DescribeInstancesResponse.Instance;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.kuding.props.AliyunEcsProperties;

public class EcsComponent {

	private final AliyunEcsProperties aliyunEcsProperties;

	private final DefaultProfile profile;

	private final IAcsClient client;

	private static final Log logger = LogFactory.getLog(EcsComponent.class);

	public EcsComponent(AliyunEcsProperties aliyunEcsProperties) {
		this.aliyunEcsProperties = aliyunEcsProperties;
		profile = DefaultProfile.getProfile(aliyunEcsProperties.getRegionId(), aliyunEcsProperties.getAccessKeyId(),
				aliyunEcsProperties.getSecret());
		client = new DefaultAcsClient(profile);
	}

	public List<Instance> getInstances(String regionId, String vpc, int pageNum, int pageSize)
			throws ServerException, ClientException {
		DescribeInstancesRequest request = new DescribeInstancesRequest();
		request.setPageNumber(pageNum);
		request.setPageSize(pageSize);
		if (vpc != null)
			request.setVpcId(vpc);
		if (regionId != null)
			request.setSysRegionId(regionId);
		DescribeInstancesResponse instancesResponse = client.getAcsResponse(request);
		List<Instance> list = instancesResponse.getInstances();
		return list;
	}

}
